<?php

declare(strict_types=1);

namespace App\Model;

use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Model;

/**
 * 用户封禁
 */
class UserForbidden extends Model
{
    protected $table = 'user_forbidden';

    protected $fillable = [
        'user_id', 'forbid_mins', 'flag', 'start_ts', 'end_ts', 'reason_type', 'reason', 'op_admin_id'
    ];

    /**
     * 封禁用户
     */
    static function doForbidden($userId = 0, $mins = 1, $start = 0, $reason_type = 0, $reason = '')
    {
        if (!$userId) return false;
        //之前记录失效
        self::cancelForbidden($userId);
        //插入新记录
        $info = [
            'user_id' => $userId,
            'forbid_mins' => $mins,
            'flag' => 1,
            'reason_type' => $reason_type,
            'reason' => $reason,
            'op_admin_id' => Admin::user()->id,
        ];
        if ($start) $info['start_ts'] = $start;
        else $info['start_ts'] = time();
        $info['end_ts'] = $info['start_ts'] + $mins * 60;
        return self::create($info);
    }

    const REASON_TYPE = [
        0 => '自定义',
        1 => '低俗',
        2 => '辱骂',
        3 => '恶意骚扰',
        4 => '资料造假',
    ];

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function adminUser()
    {
        return $this->belongsTo(AdminUsers::class, 'op_admin_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 接触禁言
     */
    static function cancelForbidden($userId = 0)
    {
        if (!$userId) return false;
        return self::where('user_id', $userId)->update(['flag' => 0]);
    }
}
